﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using EPiBoost.Core.Extensions;
using EPiBoost.Core.Infrastructure;
using EPiBoost.Core.Infrastructure.Interfaces;
using EPiBoost.Core.Infrastructure.Interfaces.Providers;
using EPiBoost.Core.Infrastructure.Providers;
using EPiServer.Configuration;

namespace BoostSite.Demo.Definitions
{
	// Note: For instructions on enabling IIS6 or IIS7 classic mode, 
	// visit http://go.microsoft.com/?LinkId=9394801
	public class Global : EPiBoost.Core.Global
	{
		 
		protected void Application_EndRequest()
		{
			if (HttpExceptionHandler.StatusCodeIsException(Context.Response.StatusCode))
			{
				HandleHttpException(Context);
			}
		}

		protected void Application_Error(object sender, EventArgs e)
		{
			Exception ex = Server.GetLastError().GetBaseException();
			HandleException(ex);
		}

		protected void Application_BeginRequest()
		{
			EPiBoost.Core.Infrastructure.CustomRedirects.CustomRedirectHandler.Current.TryRedirect(false);
		}


		private static void HandleHttpException(HttpContext context)
		{

			if (EPiBoost.Core.Configuration.Core.ErrorHandling.CustomErrorsEnabled)
			{
				var exceptionHandler = new HttpExceptionHandler
				{
					ErrorPage404Url = SiteConfiguration.Pages.ErrorPage.GetHref(),
					ErrorPage500Url = SiteConfiguration.ErrorHandling.Error500Path
				};

				exceptionHandler.HandleStatusCode(context.Response);
			} 
			else
			{
				EPiBoost.Core.Infrastructure.CustomRedirects.CustomRedirectHandler.Current.TryRedirect(true);
			}

			if (EPiBoost.Core.Configuration.Core.ErrorHandling.LogHttpExceptions)
			{
				IExceptionLogProvider logger = new ExceptionLogProvider();
				logger.LogHttpException(context);
			}
		}

		private static void HandleException(Exception ex)
		{
			if (EPiBoost.Core.Configuration.Core.ErrorHandling.LogExceptions)
			{
				IExceptionLogProvider logger = new ExceptionLogProvider();
				logger.LogException(ex);
			}
		}

	}
}
